package com.caisejingyu.whales.common;

import android.app.Activity;
import android.app.Application;
import android.arch.lifecycle.LifecycleOwner;
import android.content.Context;
import android.support.annotation.NonNull;

import com.caisejingyu.whales.common.ui.InitActivityLifecycleCallback;
import com.caisejingyu.whales.common.utils.ClassUtil;

import java.lang.ref.WeakReference;

import static com.caisejingyu.whales.common.NetworkEnvironment.ENV_TEST;

/**
 * BaseApplication
 *
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class BaseApplication extends Application {
    
    private int ENV_DEFAULT = ENV_TEST;
    
    private static BaseApplication sApp;
    private static LifecycleOwner sLastLifecycleOwner;
    private static WeakReference<Activity> sLastResumeActivityReference;
    
    private static Class<? extends InitActivityLifecycleCallback> sInitActivityLifecycleCallbackClass = InitActivityLifecycleCallback.class;
    
    @Override
    public void onCreate() {
        super.onCreate();
        sApp = this;
    }
    
    public abstract void init();
    
    protected void defaultInit() {
        
        // 初始化
        init();
        registerActivityLifecycleCallbacks(ClassUtil.newInstance(sInitActivityLifecycleCallbackClass));
    }
    
    @SuppressWarnings({"unchecked"})
    public static <T extends BaseApplication> T getApp() {
        return (T) sApp;
    }
    
    public static Context getAppContext() {
        return sApp.getApplicationContext();
    }
    
    /** 获取app环境，用于标记不同的网络环境 */
    @SuppressWarnings({"unused"})
    public int getAppEnv() {
        return ENV_DEFAULT;
    }
    
    public void SetAppEnv(@NetworkEnvironment int environment) {
        ENV_DEFAULT = environment;
    }
    
    public static LifecycleOwner getLastLifecycleOwner() {
        return sLastLifecycleOwner;
    }
    
    public static void setLastLifecycleOwner(LifecycleOwner lastLifecycleOwner) {
        sLastLifecycleOwner = lastLifecycleOwner;
    }
    
    public static Class<? extends InitActivityLifecycleCallback> getInitActivityLifecycleCallbackClass() {
        return sInitActivityLifecycleCallbackClass;
    }
    
    public static void setInitActivityLifecycleCallbackClass(@NonNull Class<? extends InitActivityLifecycleCallback> initActivityLifecycleCallbackClass) {
        sInitActivityLifecycleCallbackClass = initActivityLifecycleCallbackClass;
    }
    
    public static WeakReference<Activity> getLastResumeActivityReference() {
        return sLastResumeActivityReference;
    }
    
    public static void setLastResumeActivityReference(WeakReference<Activity> lastResumeActivityReference) {
        sLastResumeActivityReference = lastResumeActivityReference;
    }
    
}
